<?php
namespace app\attachment\event;

use app\common\controller\Addon;

class Config extends Addon
{
	public function _initialize()
    {
		parent::_initialize();
        
        $this->opAction = DcEmpty($this->query['op_action']);
	}

    //生成配置表单
	public function index()
    {
        $items = model('attachment/Form','loglic')->config(config('attachment'), $this->opAction);
        
        $this->assign('items', $items);
        
        return $this->fetch('attachment@config/index');
	}
    
    //保存配置数据
    public function update()
    {
        
		if(!$this->configWrite(input('post.'))){
		    $this->error(lang('fail'));
        }
        //返回结果
        DcCache('config_attachment', NULL);
        $this->success(lang('success'));
	}
    
    //兼容框架2.5版前（未限制op_autoload）
    private function configWrite($post=[])
    {
        //删除旧数据
        db('op')->where([
            'op_module'   => 'attachment',
            'op_controll' => 'config',
            'op_action'   => 'system',
            'op_autoload' => 'yes',
            'op_name'     => ['in',array_keys($post)],
        ])->delete();
        //表单数据
        $insertAll = [];
        foreach($post as $key=>$value){
            array_push($insertAll, [
                'op_name'      => $key,
                'op_value'     => $value,
                'op_module'    => 'attachment',
                'op_controll'  => 'config',
                'op_action'    => 'system',
                'op_order'     => 0,
                'op_autoload'  => 'yes',
                'op_status'    => 'normal',
            ]);
        }
        //批量新增
        return model('common/Op')->allowField(true)->isUpdate(false)->saveAll($insertAll);
    }
}